<template>
  <div class="d-inline-block">
    <v-chip v-for="(subItem,index) in label" v-bind:key="index" close @input="closeLabel($event, index)" @click="edit(index)">{{subItem}}</v-chip>
    <v-icon @click="newLabel">add</v-icon>
    <v-dialog v-if="dialog.visible" v-model="dialog.visible" max-width="200px">
      <v-card>
        <v-card-text>
          <v-form ref="form" v-model="valid" lazy-validation>
            <v-container>
              <v-layout wrap>
                <v-flex xs12>
                  <v-text-field :rules="rules.label" v-model="labelStr" label="标签" required></v-text-field>
                </v-flex>
              </v-layout>
            </v-container>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="dialog.visible=false">关闭</v-btn>
          <v-btn color="blue darken-1" flat @click="submitLabel">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: 'Label',
  model: {
    prop: 'label',
    event: 'cc'
  },
  props: {
    label: {}
  },
  data: () => ({
    labelStr: '',
    dialog: {
      visible: false,
      index: ''
    },
    rules: {
      label: [v => !!v || '标签必须填写', v => (v && v.indexOf(' ') === -1) || '标签不能包含空格']
    },
    valid: true
  }),
  methods: {
    closeLabel (data, index) {
      this.stopPropagation()
      let labelS = []
      for (let i = 0; i < this.label.length; i++) {
        if (i !== index) {
          labelS.push(this.label[i])
        }
      }
      this.$emit('cc', labelS)
    },
    stopPropagation (e) {
      e = e || window.event
      if (e.stopPropagation) {
        e.stopPropagation()
      } else {
        e.cancelBubble = true
      }
    },
    edit (index) {
      this.labelStr = this.label[index]
      this.dialog.index = index
      this.dialog.visible = true
    },
    submitLabel () {
      if (!this.$refs.form.validate()) {
        return
      }
      if (this.dialog.index === '') {
        let label = this.label
        label.push(this.labelStr)
        this.$emit('cc', label)
        this.dialog.visible = false
      } else {
        let label = []
        for (let i = 0; i < this.label.length; i++) {
          if (i !== this.dialog.index) {
            label.push(this.label[i])
          } else {
            label.push(this.labelStr)
          }
        }
        this.$emit('cc', label)
        this.dialog.visible = false
      }
    },
    newLabel () {
      this.labelStr = ''
      this.dialog.index = ''
      this.dialog.visible = true
    }
  }
}
</script>

<style scoped>

</style>
